from typing import Dict, Any, Callable, List

# 简单工具注册表
_TOOL_REGISTRY: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {}


def tool(name: str):
    def decorator(func: Callable[[Dict[str, Any]], Dict[str, Any]]):
        _TOOL_REGISTRY[name] = func
        return func

    return decorator


def list_tools() -> List[Dict[str, Any]]:
    return [
        {
            "name": name,
            "description": func.__doc__ or "",
            "schema": getattr(func, "__schema__", {"type": "object"}),
        }
        for name, func in _TOOL_REGISTRY.items()
    ]


def call_tool(name: str, params: Dict[str, Any]) -> Dict[str, Any]:
    if name not in _TOOL_REGISTRY:
        return {"ok": False, "error": f"Unknown tool: {name}"}
    try:
        result = _TOOL_REGISTRY[name](params)
        if "ok" not in result:
            result["ok"] = True
        return result
    except Exception as e:
        return {"ok": False, "error": str(e)}


@tool("retrieve_logs")
def retrieve_logs_tool(params: Dict[str, Any]) -> Dict[str, Any]:
    """
    从向量存储中检索与查询最相关的日志片段。
    入参: { "query": str, "top_k": int=5 }
    出参: { "documents": [ { "content": str, "score": float } ] }
    """
    query = (params.get("query") or "").strip()
    top_k = int(params.get("top_k") or 5)
    if not query:
        return {"ok": False, "error": "query is required"}

    # 避免循环导入：在函数内部延迟导入
    from .services import get_vector_system

    system = get_vector_system()
    docs = system.retrieve_logs(query, top_k=top_k) or []
    return {"ok": True, "documents": docs}
